#!/bin/bash
set -e

if [ -z "$1" ]; then
    echo "Error: appID parameter is required."
    echo "Usage: $0 <appID>"
    exit 1
fi

APPID="$1"

ZIP_URL="http://dl.snodehub.com/download/linux/oem/lotso-oem_v1.9.2_2025-05-08.zip"
ZIP_PATH="/root/lotso-oem_v1.9.2_2025-05-08.zip"
INSTALL_DIR="/data/.lotso"
LOG_DIR="/var/log/wxedge"

apt update
apt install -y unzip
mkdir -p "$INSTALL_DIR" "$LOG_DIR"
curl -o "$ZIP_PATH" "$ZIP_URL"
unzip -o "$ZIP_PATH" -d "$INSTALL_DIR"

deviceSN=$(perl -n -e 'if (/snum=([^\s]+)/) { print "$1\n"; exit }' /proc/cmdline)

SERVICE_PATH="/etc/systemd/system/lotso.service"
cat > "$SERVICE_PATH" << EOF
[Unit]
Description=Lotso Edge Service
After=network.target

[Service]
Type=simple
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/lotso run --enableShareplan --appID=$APPID --deviceSN=$deviceSN
StandardOutput=journal
StandardError=journal
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

chmod 644 "$SERVICE_PATH"
systemctl daemon-reload
systemctl enable --now lotso.service
systemctl status lotso.service
